package com.xposed.openfire.smack;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.MenuItem;

import com.xposed.openfire.smack.abstracts.AbstractBaseActivity;
import com.xposed.openfire.smack.adapter.MainFragmentPagerAdapter;
import com.xposed.openfire.smack.entity.ChatMessage;
import com.xposed.openfire.smack.entity.FriendAdd;
import com.xposed.openfire.smack.entity.FriendAddDao;
import com.xposed.openfire.smack.entity.FriendGoodDao;
import com.xposed.openfire.smack.fragment.ChatFragment;
import com.xposed.openfire.smack.fragment.FriendFragment;
import com.xposed.openfire.smack.fragment.MineFragment;
import com.xposed.openfire.smack.utils.ACache;
import com.xposed.openfire.smack.utils.JsonUtils;
import com.xposed.openfire.smack.utils.LogUtils;
import com.xposed.openfire.smack.xmpp.XmppConnection;

import org.greenrobot.greendao.query.QueryBuilder;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.roster.RosterEntry;
import org.jivesoftware.smack.roster.packet.RosterPacket;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;

public class MainActivity extends AbstractBaseActivity implements BottomNavigationView.OnNavigationItemSelectedListener, ViewPager.OnPageChangeListener {

    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.bottom_navigation_view)
    BottomNavigationView navigationView;

    private ProgressDialog progressDialog;
    private MainFragmentPagerAdapter pageAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

        ACache aCache = ACache.get(this);
        String appUserName = APPOpenfireSmack.getEntityFullJid().asBareJid().getLocalpartOrNull().intern();
        String cacheUserName = aCache.getAsString("user_name");
        if (!TextUtils.isEmpty(cacheUserName) && !cacheUserName.equals(appUserName)) {
            APPOpenfireSmack.getDaoSession().getChatMessageDao().deleteAll();
            APPOpenfireSmack.getDaoSession().getChatRecordDao().deleteAll();
            APPOpenfireSmack.getDaoSession().getFriendGoodDao().deleteAll();
        }
        aCache.put("user_name", appUserName);

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new ChatFragment());
        fragments.add(new FriendFragment());
        fragments.add(new MineFragment());
        pageAdapter = new MainFragmentPagerAdapter(getSupportFragmentManager(), fragments);
        navigationView.setOnNavigationItemSelectedListener(this);
        viewPager.addOnPageChangeListener(this);
        viewPager.setAdapter(pageAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        XmppConnection.getInstance().closeConnection();
    }

    @Override
    public void onEventMainThread(Object object) {
        super.onEventMainThread(object);
        if (object instanceof ChatMessage) {
            LogUtils.e(JsonUtils.objectToString(object));
            APPOpenfireSmack.getDaoSession().getChatMessageDao().insert((ChatMessage) object);
        }else if (object instanceof Presence) {
            Presence presence = (Presence) object;
            String from = presence.getFrom().asBareJid().toString();
            String to = presence.getTo().asBareJid().toString();
            StringBuilder sb = new StringBuilder();
            switch (presence.getType()) {
                case subscribe:
                    RosterEntry entry = XmppConnection.getInstance().getEntries(from);
                    if (entry != null && entry.getType() == RosterPacket.ItemType.to) {
                        XmppConnection.getInstance().subscribed(from, Presence.Type.subscribed);
                    } else {

                        FriendAddDao addDao = APPOpenfireSmack.getDaoSession().getFriendAddDao();
                        QueryBuilder<FriendAdd> builder = addDao.queryBuilder().where(FriendAddDao.Properties.From.eq(from));
                        FriendAdd add = new FriendAdd();
                        add.setFrom(from);
                        add.setTo(to);
                        add.setType(presence.getType().toString());
                        SimpleDateFormat sdf = new SimpleDateFormat(("yyyy年MM月dd日 HH:mm:ss"), Locale.CHINA);
                        add.setTime(sdf.format(new Date(System.currentTimeMillis())));
                        if (builder.unique() != null){
                            add.setId(builder.unique().getId());
                            addDao.update(add);
                        } else {
                            addDao.insert(add);
                        }
//                        subscribed(from, Presence.Type.subscribed);
//                        addCreateFriend(from, null, null);
                    }
                    sb.append("请求添加为好友");
                    break;
                case subscribed:
                    sb.append("同意订阅");
                    break;
                case unsubscribe:
                    sb.append("取消订阅");
                    break;
                case unsubscribed:
                    sb.append("拒绝订阅");
                    break;
                case unavailable:
                    sb.append("离线");
                    break;
                case available:
                    sb.append("上线");
                    break;
            }
            LogUtils.e(sb.append("，from：").append(from).append("，to：").append(to).toString());
        }

    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.navigation_chat:
                viewPager.setCurrentItem(0);
                return true;
            case R.id.navigation_friend:
                viewPager.setCurrentItem(1);
                return true;
            case R.id.navigation_mine:
                viewPager.setCurrentItem(2);
                return true;
            default:
                break;
        }
        return false;
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        navigationView.getMenu().getItem(i).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }


//    @OnClick({R.id.btn_exit})
//    public void onViewClicked(View view) {
////        LogUtils.e(JsonUtils.objectToString());
////        XmppConnection.getInstance().sendChatMessage("admin", "你好！");
////        Intent intent = new Intent(this,UserLoginActivity.class);
////        startActivity(intent);
////        finish();
//    }


//        new Thread(new Runnable() {
//        @Override
//        public void run() {
//            try {
//                Log.e("TAG", "初始化配置:");
//                InetAddress inetAddress = InetAddress.getByName("192.168.88.133");
//                XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
//                        .setUsernameAndPassword("linlimin", "linlimin2")
//                        .setXmppDomain("192.168.88.133")
//                        .setHostAddress(inetAddress)
//                        .setPort(5222)
//                        .setSendPresence(false)
//                        .setCompressionEnabled(true)
//                        .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
//                        .build();
//                Log.e("TAG", "建立连接:");
//                connection = new XMPPTCPConnection(config);
//                connection.connect();
//
//
//                if (connection.isConnected()) {
//                    Log.e("TAG", "连接成功:");
//
//
//                    try {
//                        AccountManager.getInstance(connection).sensitiveOperationOverInsecureConnection(true);
//                        Map<String,String> map = new HashMap<>();
//                        map.put("name","hello1");
//                        map.put("email","hello1@outlook.com");
//                        AccountManager.getInstance(connection).createAccount(Localpart.from("hello1"), "hello1",map);
//                        Log.e("TAG","---" + 1);
//                    } catch (SmackException.NoResponseException e) {
//                        e.printStackTrace();
//                        Log.e("TAG", "NoResponseException:" + e.getMessage());
//                    } catch (XMPPException.XMPPErrorException e) {
//                        e.printStackTrace();
//                        if (e.getStanzaError().getCondition() == StanzaError.Condition.conflict) {
//                            Log.e("TAG", "XMPPErrorException:" + "用户已存在");
//                        }
//                        Log.e("TAG", "XMPPErrorException:" + e.getMessage());
//                    } catch (SmackException.NotConnectedException e) {
//                        e.printStackTrace();
//                        Log.e("TAG", "NotConnectedException:" + e.getMessage());
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                        Log.e("TAG", "InterruptedException:" + e.getMessage());
//                    }
//                    connection.login();
//                    Log.e("TAG", "登录成功:");
//                }
//
//            } catch (XmppStringprepException e) {
//                e.printStackTrace();
//                Log.e("TAG", "XmppStringprepException:" + e.getMessage());
//            } catch (XMPPException e) {
//                e.printStackTrace();
//                if (e.getMessage().contains(SASLError.not_authorized.toString()))
//
//                    Log.e("TAG", "etertertwer:" + SASLError.not_authorized);
//                Log.e("TAG", "XMPPException:" + e.getLocalizedMessage());
//            } catch (SmackException e) {
//                e.printStackTrace();
//                Log.e("TAG", "SmackException:" + e.getMessage());
//            } catch (IOException e) {
//                e.printStackTrace();
//                Log.e("TAG", "IOException:" + e.getMessage());
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//                Log.e("TAG", "InterruptedException:" + e.getMessage());
//            }
//        }
//    }).start();
}
